package com.xiaolee.sso.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 用户身份认证
 *
 * @author lizhongcheng@didiglobal.com
 * @version 1.0
 * @date 2021-05-31 20:37:24
 * @description
 */
@RequestMapping(value = "/auth")
@RestController
public class AuthController {
    private static final String AUTH_USER_NAME = "mingjing";
    private static final String AUTH_USER_PASSWORD = "mingjing";

    /**
     * 认证map
     */
    private Map<String, String> authMap = new HashMap<>();



    @PostMapping("/login")
    public String login(HttpServletRequest request, HttpServletResponse response) {
        String userName = request.getParameter("name");
        String password = request.getParameter("password");

        if (AUTH_USER_NAME.equals(userName) && AUTH_USER_PASSWORD.equals(password)) {
            // 返回cookie是为了再请求此登陆服务的时候可以无需输入用户名密码
            String ticket = "ticket_" + UUID.randomUUID().toString();
            Cookie loginCookie = new Cookie("ticket", ticket);
            Cookie nameCookie = new Cookie("name", userName);
            authMap.put(userName, ticket);

            response.addCookie(loginCookie);
            response.addCookie(nameCookie);

            return ticket;
        }

        return "";
    }
}
